<?php

/**
 * 用户信息BUS
 */

namespace App\Context;

use App\Constants\RedisKey;
use App\Model\AdminUser;
use App\Model\AdminUserData;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class UserInfoContext {
    public array $userInfo;

    public function setUserInfo($userInfo): UserInfoContext {
        $this->userInfo = $userInfo;

        return $this;
    }

    /**
     * 更新用户信息
     * @param array $data
     * @param bool $isDetail
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function updateUserInfo(array $data, bool $isDetail = false): void {
        $redis = (ApplicationContext::getContainer())->get(Redis::class);
        $apiAuth = $redis->get(RedisKey::ADMIN_LOGIN_ID . ':' . $this->userInfo['id']);

        if ($isDetail) {
            AdminUserData::query()->where('uid', $this->userInfo['id'])->update($data);
            $this->userInfo['user_data'] = AdminUserData::query()->where('uid', $this->userInfo['id'])->first();
        } else {
            AdminUser::query()->where('id', $this->userInfo['id'])->update($data);
            $detail = $this->userInfo['user_data'];
            $this->userInfo = AdminUser::query()->where('id', $this->userInfo['id'])->first()->toArray();
            $this->userInfo['user_data'] = $detail;
        }

        $redis = (ApplicationContext::getContainer())->get(Redis::class);
        $redis->set(RedisKey::ADMIN_LOGIN_AUTH . ':' . $apiAuth, json_encode($this->userInfo), config('apiadmin.online_time'));
    }

}
